import { LockOutlined, UserOutlined } from '@ant-design/icons'
import { Alert, Tabs } from 'antd'
import React, { useEffect, useState } from 'react'
import ProForm, { ProFormText } from '@ant-design/pro-form'
import { connect, FormattedMessage, history, useIntl } from 'umi'
import styles from './index.less'

const LoginMessage = ({ content }) => (
  <Alert
    style={{
      marginBottom: 24,
    }}
    message={content}
    type="error"
    showIcon
  />
)

const Login = (props) => {
  const { userLogin = {}, submitting } = props
  const { status, type: loginType } = userLogin
  const [type, setType] = useState('account')
  const intl = useIntl()

  //能避免在组件更新执行useEffect(通常用于请求数据 事件处理)，只会在组件mount时执行
  useEffect(() => {
    const user = localStorage.getItem('adminInfo')
    if (user) {
      history.replace('/')
    }
  }, [])

  const handleSubmit = (values) => {
    const { dispatch } = props
    dispatch({
      type: 'login/login',
      payload: { ...values, type },
    })
  }

  return (
    <div className={styles.main}>
      <ProForm
        initialValues={{
          autoLogin: true,
        }}
        submitter={{
          render: (_, dom) => dom.pop(),
          submitButtonProps: {
            loading: submitting,
            size: 'large',
            style: {
              width: '100%',
            },
          },
        }}
        onFinish={async (values) => {
          handleSubmit(values)
          return Promise.resolve()
        }}
      >
        <Tabs activeKey={type} onChange={setType}>
          <Tabs.TabPane
            key="account"
            tab={intl.formatMessage({
              id: 'pages.login.accountLogin.tab',
              defaultMessage: '账户密码登录',
            })}
          />
        </Tabs>

        {status === 'error' && !submitting && (
          <LoginMessage
            content={intl.formatMessage({
              id: 'pages.login.accountLogin.errorMessage',
              defaultMessage: '账户或密码错误（admin/ant.design)',
            })}
          />
        )}
        {type === 'account' && (
          <>
            <ProFormText
              name="username"
              fieldProps={{
                size: 'large',
                prefix: <UserOutlined className={styles.prefixIcon}/>,
              }}
              placeholder="请输入用户名"
              rules={[
                {
                  required: true,
                  message: (
                    <FormattedMessage
                      id="pages.login.username.required"
                      defaultMessage="请输入用户名!"
                    />
                  ),
                },
              ]}
            />
            <ProFormText.Password
              name="password"
              fieldProps={{
                size: 'large',
                prefix: <LockOutlined className={styles.prefixIcon}/>,
              }}
              placeholder="请输入密码"
              rules={[
                {
                  required: true,
                  message: (
                    <FormattedMessage
                      id="pages.login.password.required"
                      defaultMessage="请输入密码！"
                    />
                  ),
                },
              ]}
            />
          </>
        )}

        <div
          style={{
            marginBottom: 24,
          }}
        >
          <a
            style={{
              float: 'right',
            }}
          >
          </a>
        </div>
      </ProForm>
    </div>
  )
}

export default connect(({ login, loading }) => ({
  userLogin: login,
  submitting: loading.effects['Login/Login'],
}))(Login)
